'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'

interface HotArticle {
  id: number
  post_id: number
  title: string
  summary?: string
  publishTime?: string
  viewCount?: number
  likeCount?: number
  commentCount?: number
  coverImage?: string
  tags?: string
  categoryName?: string
}

const HotArticleListPage = () => {
  const [hotArticles, setHotArticles] = useState<HotArticle[]>([])
  const [loading, setLoading] = useState(true)
  const [message, setMessage] = useState<{ type: 'success' | 'error' | ''; text: string }>({ type: '', text: '' })

  // 获取热门文章列表
  useEffect(() => {
    fetchHotArticles()
  }, [])

  const fetchHotArticles = async () => {
    try {
      setLoading(true)
      const response = await fetch('/api/hot-articles', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      })

      const result = await response.json()

      if (result.code === 200) {
        setHotArticles(result.data)
      } else {
        setMessage({ type: 'error', text: result.message || '获取热门文章列表失败' })
      }
    } catch (error) {
      setMessage({ type: 'error', text: '获取热门文章列表过程中发生错误' })
    } finally {
      setLoading(false)
    }
  }

  // 删除热门文章（软删除）
  const handleDelete = async (id: number) => {
    if (!confirm('确定要删除这篇文章吗？')) {
      return
    }

    try {
      const response = await fetch('/api/hot-articles', {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ id })
      })

      const result = await response.json()

      if (result.code === 200) {
        setMessage({ type: 'success', text: '删除成功' })
        // 从列表中移除已删除的文章
        setHotArticles(prev => prev.filter(article => article.id !== id))
      } else {
        setMessage({ type: 'error', text: result.message || '删除失败' })
      }
    } catch (error) {
      setMessage({ type: 'error', text: '删除过程中发生错误' })
    }
  }

  return (
    <div className="container mx-auto p-4 max-w-6xl">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold">热门文章管理</h1>
        <Link 
          href="/wp/add-hot" 
          className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
        >
          添加热门文章
        </Link>
      </div>
      
      {/* 消息提示 */}
      {message.text && (
        <div className={`mb-4 p-3 rounded ${message.type === 'success' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
          {message.text}
        </div>
      )}

      {loading ? (
        <div className="text-center py-8">加载中...</div>
      ) : hotArticles.length === 0 ? (
        <div className="text-center py-8">
          <p className="text-gray-500 mb-4">暂无热门文章</p>
          <Link 
            href="/wp/add-hot" 
            className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
          >
            添加第一篇热门文章
          </Link>
        </div>
      ) : (
        <div className="bg-white shadow overflow-hidden rounded-lg">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  标题
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  浏览量
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  点赞数
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  评论数
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {hotArticles.map((article) => (
                <tr key={article.id}>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm font-medium text-gray-900">{article.title}</div>
                    {article.summary && (
                      <div className="text-sm text-gray-500 mt-1 line-clamp-2">{article.summary}</div>
                    )}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {article.viewCount}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {article.likeCount}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {article.commentCount}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <Link 
                      href={`/wp/add-hot?id=${article.id}`} 
                      className="text-indigo-600 hover:text-indigo-900 mr-4"
                    >
                      编辑
                    </Link>
                    <button
                      onClick={() => handleDelete(article.id)}
                      className="text-red-600 hover:text-red-900"
                    >
                      删除
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}

export default HotArticleListPage